package com.andy.service.impl;

import cn.hutool.core.date.DateUtil;
import com.andy.infrastructure.util.FileUtil;
import com.andy.infrastructure.util.FreeMarkerUtil;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YoubusService {

    @Autowired
    private freemarker.template.Configuration cfg;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private FreeMarkerUtil freeMarkerUtil;

    /**
     * 创建有巴action
     * @param input
     * @return
     */
    public String createYoubusActionClass(String input){
        //1-class的内容
        String ftlName = "youbus_action_class.ftl";
        String ftlString = freeMarkerUtil.getFreeMarkerString(cfg, ftlName, input);
        //生成文件
        Map<String, Object> map =  freeMarkerUtil.putInput(input);
        String fileName = (String)map.get("actionName_Iii")+".java";
        String filePath = "D:\\autoOutput";
        try {
            //创建文件
            FileUtil.createFile(fileName,ftlString,filePath);
            //弹出框体
            FileUtil.popupDir(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //2-其他辅助内容
        String ftlName2 = "youbus_action_assist.ftl";
        String ftlString2 = freeMarkerUtil.getFreeMarkerString(cfg, ftlName2, input);
        System.out.println(ftlString2);

        return ftlString2;
    }

    private final Map<String,String> sqlType = new HashMap<String,String>(){
        {
            put("int", "Integer");
            put("varchar", "String");
            put("char", "String");
            put("datetime", "Date");
            put("date", "Date");
            put("decimal", "Double");
        }
    };

    /**
     * 生成po文件
     * @param input
     * @return
     * @throws Exception
     */
    public String createSqlPO(String input){
        Connection conn = null;
        try{
            //拆解入参
            Map<String, Object> map =  freeMarkerUtil.putInput(input);
            String tableName = (String)map.get("tableName");
            conn = dataSource.getConnection();
            Statement stmt = conn.createStatement();

            //1-整理字段数据
            List<Map<String, Object>> columnList = new ArrayList <>();
            //字段名、描述、类型
            ResultSet rsFields = stmt.executeQuery(" show full fields from " + tableName + "");
            for (; rsFields.next();) {
                Map<String,Object> tempMap = new HashMap <>();
                tempMap.put("columnName",rsFields.getString("FIELD"));
                tempMap.put("columnComment",rsFields.getString("COMMENT"));
                //类型：varchar(60) int(11) 这样子的，需要把括弧去掉
                String type = rsFields.getString("type");
                if(type.indexOf("(")>0){
                    type = type.substring(0,type.indexOf("("));
                }
                tempMap.put("columnType",sqlType.get(type));
                //增强大小写形式
                tempMap = freeMarkerUtil.advanceMapCase(tempMap);
                //放入列表
                columnList.add(tempMap);
            }
            //放入大map中
            map.put("columnList",columnList);

            //2-整理表数据
            ResultSet rstComment=stmt.executeQuery("SHOW CREATE TABLE "+tableName);
            for (; rstComment.next();) {
                String tableComment = rstComment.getString(2).substring(rstComment.getString(2).lastIndexOf("COMMENT")+9,rstComment.getString(2).length()-1);
                map.put("tableComment", tableComment);
                break;
            }
            //模板生成vo字符串
            String ftlName = "youbus_sql_po.ftl";
            Template t = cfg.getTemplate(ftlName);
            // 输出到控制台
            StringWriter writer = new StringWriter();
            t.process(map, writer);
            String poStr = writer.toString();

            //生成文件
            String filePath = "D:\\autoOutput";
            try {
                String fileName = (String)map.get("tableName_Iii")+".java";
                //创建文件
                FileUtil.createFile(fileName,poStr,filePath);
                //弹出框体
                FileUtil.popupDir(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


        return "";
    }





}
